package com.mgq.juc.design.order.v1;

import lombok.extern.slf4j.Slf4j;

/**
 * @author MaGuangQi
 * 顺序打印 2和1 (先打印2,再打印1) 基于wait /notify实现
 * @date 2021-12-17 10:28
 **/
@Slf4j
public class OrderPrint {
    private static final Object lock = new Object();
    //标记1是否已经打印
    private static boolean printOne = false;

    public static void main(String[] args) {
    //先打印1,然后打印2
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                log.debug("2");
                printOne =true;
                lock.notify();
            }
        },"t1");

        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                //如果1 没有打印,等着通知
                // 使用wait,必须用while,防止虚假唤醒
                while (!printOne) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("1");
            }
        },"t2");
        t2.start();
        t1.start();
    }
}
